package net.lovesrc.allin.biz.dida;

import com.google.common.collect.Maps;
import com.zhouzhou.fastjava.util.StringKit;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

/**
 * User: liuzheqiang
 * Date: 2018/4/2
 * Time: 14:09
 */
class SignUtils {

    public static void signParams(Map<String, Object> params) {

        String ts = timestamp();
        String vkey = SignUtils.sign(ts);
        String sign = SignUtils.sign(params, vkey);

        params.put("ts", ts);
        params.put("vkey", vkey);
        params.put("sig", sign);
    }

    private static String sign(Object[] paramArrayOfObject) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < paramArrayOfObject.length; i++) {
            str.append(paramArrayOfObject[i]);
        }
        return StringKit.md5(StringKit.md5(str.toString().toUpperCase()).toUpperCase() + "kx123456789012345678901234567890").toUpperCase();
    }

    private static String sign(String paramString) {
        return sign(new String[]{"dida_app", paramString});
    }

    private static String sign(Map<String, Object> paramsTreeMap, String paramString) {
        TreeMap<String, Object> targetMap = Maps.newTreeMap();
        targetMap.putAll(paramsTreeMap);
        {
            targetMap.remove("actid");
            targetMap.remove("version");
            targetMap.remove("token");
            targetMap.remove("ts");
            targetMap.remove("vkey");
            targetMap.remove("mobiletype");
        }
        StringBuilder str = new StringBuilder();
        for (Map.Entry<String, Object> entry : targetMap.entrySet()) {
            str.append(entry.getKey());
            str.append("=");
            if (entry.getValue() != null) {
                str.append(entry.getValue());
            }
        }
        return StringKit.md5(str.toString() + paramString);
    }

    private static String timestamp() {
        return new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date(System.currentTimeMillis()));
    }

}
